import { getServiceById, getWidgetOrField, transformTreeToObject } from '@/utils/util'
import { getComponentValueToService } from '@/components/event-behavior/query/parameter-helper'
import XEUtils, { isBoolean } from 'xe-utils'
import { ElMessage } from 'element-plus'
import { executeMultiple } from '@/api/executor'
import { isArray, isEmpty } from 'lodash-es'

export default {
  data() {
    return {
      loadingFlag: false,
    }
  },
  methods: {
    /**
     * 从服务注册读取数据
     * @param serviceId
     */
    async loadDataFromService(serviceId) {
      let curServiceId = serviceId ?? getWidgetOrField(this).options.service.id
      const executeService = getServiceById(this.formConfig, curServiceId)
      const postParmas = {
        svvId: curServiceId,
      }
      if (!isEmpty(executeService.inputModelTree)) {
        const postData = transformTreeToObject(executeService.inputModelTree, (node) => {
          // 获取组件值并返回，防止 undefined 返回 null
          if (isArray(node?.component) && node?.component?.length > 0) {
            return this.getWidgetRef(node.component[0])?.getValue()
          }
          return null
        })
        postParmas.dataJson = postData
      }
      const res = await executeMultiple(postParmas)?.catch((err) => {
        console.error(`获取服务数据失败`)
      })
      // console.log('loadDataFromService', res)
      return res
    },
    /**
     * 从服务注册读取数据
     * @returns {Promise<void>}
     */
    async loadData() {
      // console.log('designState', this.designState)
      if (this.designState) {
        return
      }
      const widget = getWidgetOrField(this)
      console.log(`${widget.id} start load data`)

      if (
        this.designState ||
        !widget.options.service.enabled ||
        !getWidgetOrField(this).options.service.id
      ) {
        return
      }
      if (isBoolean(this.loadingFlag)) {
        /*if (!widget.options.remote) {
          widget.options.disabled = true
        }*/
        this.loadingFlag = true
      }

      const res = await this.loadDataFromService().finally(() => {
        this.loadingFlag = false
      })
      switch (widget.type) {
        case 'select':
        case 'checkbox':
        case 'radio':
          this.loadOptions(res)
          break
        case 'data-table':
          // console.log('loadDataFromService', res, widget)
          this.tableData = res
          this.initFieldData()
      }
      if (widget.options.onDataLoaded) {
        let customFn = new Function('data', widget.options.onDataLoaded)
        customFn.call(this, res)
      }
    },
    /**
     * 由dialog,drawer,render组件调用，可以绑定多个服务
     * @param keys 服务keys
     */
    async loadDataFromServiceByKeys(keys) {
      const curServices = getServiceById(this.formConfig, keys)
      const resAll = await Promise.all(
        curServices.map(async (curService) => {
          const requestParams = getComponentValueToService.call(this, curService)
          const res = await getServiceData(curService, requestParams).catch((err) => {
            console.error(`获取服务数据失败,${curService.name}`)
          })
          return res
        }),
      )
      console.log('loadDataFromServiceByKeys', resAll)
      const serviceRes = []
      resAll.reduce((pre, cur, index) => {
        pre.push(cur.data.result.rows[0])
        return pre
      }, serviceRes)
      return serviceRes
    },
    /**
     * 通过代码提交服务时，会判断参数是否存在于服务的入参中，如果不存在则报错，如果存在则进行合并后提交
     * @param serviceKey 服务key
     * @param params 通过代码提交时传递的参数
     * @returns {Promise<*>}
     */
    async postService(serviceKey, params) {
      let curServiceKey = serviceKey ?? getWidgetOrField(this).options.service.key
      const curService = getServiceById(this.formConfig, curServiceKey)
      if (!curService) {
        ElMessage.error(`${serviceKey}服务不存在!`)
        return
      }
      const componentValueMap = getComponentValueToService.call(this, curService)
      if (params) {
        if (!XEUtils.isObject(params)) {
          ElMessage.error(`${serviceKey}服务参数必须是对象!`)
          return
        }
        /**
         * 如果传入的参数不包含在参数定义中，则终止,否则将传入的参数与组件的值进行合并
         */
        if (
          !Object.keys(params).every((key) => {
            if (!curService.parameterDefinitions.some((item) => item.name === key)) {
              ElMessage.error(`提交的参数必须存在服务中，${key}参数不存在于${curService.name}中!`)
              return false
            }
            return true
          })
        ) {
          return
        } else {
          Object.assign(componentValueMap, params)
        }
      }
      // console.log('postService', curService);
      const res = await getServiceData(curService, postParams).catch((err) => {
        console.error(`获取服务数据失败,${curService.name}`)
      })
      return res
    },
    async getService(serviceKey, setFormFlag = true) {
      const response = await this.loadDataFromService(serviceKey)
      const result = response.data.result.rows
      if (setFormFlag && result?.length === 1) {
        this.setFormDataByService(result)
      }
      return result
    },
  },
}
